/*
 * Copyright (c) 2023, 2024,yzc.cn All rights reserved.
 *
 */
package com.by.server.impl;

import com.by.common.utils.AutoCode;
import com.by.common.utils.AutoData;
import com.by.mapper.PurValuationDetailsMapper;
import com.by.mapper.PurValuationMapper;
import com.by.mapper.PurValuationProMapper;
import com.by.pojo.PurValuation;
import com.by.pojo.PurValuationPro;
import com.by.server.PurValuationServer;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>Project: erp-cloud-api - PurValuationServerImpl</p>
 * <p>Powered by yzc On 2024-01-10 20:42:45</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */
@Service
public class PurValuationServerImpl implements PurValuationServer {

    @Autowired
    PurValuationMapper purValuationMapper;

    @Autowired
    PurValuationDetailsMapper purValuationDetailsMapper;

    @Autowired
    PurValuationProMapper purValuationProMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    @Transactional
    public int save(PurValuation purValuation) {
        //根据来源获得Code前缀
        String code =  AutoCode.autoCodePrefix("定价")+ AutoData.getNowData();
        //根据Code前缀查询最大的Code
        String maxCode =  purValuationMapper.maxCode(code);
        //获得新的Code
        String newCode =AutoCode.getNewCode(maxCode,code);

        purValuation.setCode(newCode);

        //设置关联字段
        purValuation.getPurValuationPro().setValuationCode(newCode);
        //保存询价产品
        purValuationProMapper.insert(purValuation.getPurValuationPro());
        //遍历询价详情list集合
        purValuation.getPurValuationDetailsList().forEach(pv->{
            //设置关联字段
            pv.setValuationCode(newCode);
            //保存询价详情
            purValuationDetailsMapper.insert(pv);
        });

        int rs = purValuationMapper.insert(purValuation);
        if (rs > 0) {
            String inquiryCode = purValuation.getInquiryCode();
            rabbitTemplate.convertAndSend("valuationStatusExchange","VStatus",inquiryCode);
        }

        return rs;
    }
}
